package response

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type statusType string

var (
	StatusErr statusType = "error"
	StatusOk  statusType = "ok"
)

type Response struct {
	Status  statusType `json:"status"`
	Data    any        `json:"data,omitempty"`
	Message string     `json:"message,omitempty"`
}

func (res *Response) RespOk(w http.ResponseWriter, data any) {
	w.WriteHeader(http.StatusOK)
	res.Status = StatusOk
	res.Data = data
}

func (res *Response) BadRequest(w http.ResponseWriter, message string) {
	w.WriteHeader(http.StatusBadRequest)
	res.Status = StatusErr
	res.Message = message
}

func (res *Response) MethodNotAllowed(w http.ResponseWriter) {
	w.WriteHeader(http.StatusMethodNotAllowed)
	res.Status = StatusErr
	res.Message = "http.Method非法"
}

func (res *Response) ServerErr(w http.ResponseWriter, message string) {
	w.WriteHeader(http.StatusInternalServerError)
	res.Status = StatusErr
	res.Message = message
}

func (res *Response) Send(w http.ResponseWriter) {
	encoder := json.NewEncoder(w)
	err := encoder.Encode(res)
	if err != nil {
		fmt.Println(err)
		res.ServerErr(w, "server error")
		return
	}
}
